<template>
  <div class="ageReformApply-info">
    <el-scrollbar height="calc( 100vh - 150px)">
      <div style="padding: 10px 0 20px">
        <el-card class="box-card" shadow="always" style="background: #fafafa">
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>基本信息</span>
            </div>
          </template>
          <el-row style="padding: 10px 40px">
            <el-col :span="8"><span>老人姓名1:</span><span style="margin-left: 10px">{{ basicInfo.name }}</span></el-col>
            <el-col :span="8"><span style="display: inline-block; width: 68px; text-align: right">性别:</span><span style="margin-left: 10px">{{
                sys_user_sex.find((item) => item.value == basicInfo.sex)
                  ? sys_user_sex.find((item) => item.value == basicInfo.sex)
                      .label
                  : ""
              }}</span>
            </el-col>
            <el-col :span="8"><span style="display: inline-block; width: 68px; text-align: right">年龄:</span><span style="margin-left: 10px">{{basicInfo.age }}</span></el-col>
            <el-col :span="24" style="margin-top: 30px">
              <span>家庭住址:</span><span style="margin-left: 10px">{{basicInfo.address }}</span>
            </el-col>
          </el-row>
        </el-card>
        <el-card class="box-card" shadow="always" style="background: #fafafa; margin-top: 15px">
          <template #header>
            <div class="card-header" style="
                padding-bottom: 4px;
                display: flex;
                align-items: center;
                justify-content: space-between;
              ">
              <span>适老化改造产品</span>
            </div>
          </template>
          <div>
            <div>
              <span>合计金额：</span><span>{{ total }}元</span>
            </div>
            <div style="margin-top: 10px">
              <el-table v-loading="loading" :data="evaluationCriteriaList" stripe border max-height="250">
                <el-table-column label="序号" type="index" width="80" align="center"/>
                <el-table-column label="产品名称" align="center" prop="name" />
                <el-table-column label="单价（元）" align="center" prop="unitPrice"/>
                <el-table-column label="数量" align="center" prop="number" />
                <el-table-column label="总价（元）" align="center" prop="totalPrice"/>
                <el-table-column label="设备编号" align="center" prop="imei" />
                <el-table-column label="施工单位" align="center" prop="constructionUnit"/>
                <el-table-column label="安装人员" align="center" prop="constructionPersonnel"/>
                <el-table-column label="施工日期" align="center" prop="constructionDate"/>
                <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
                  <template #default="scope">
                    <el-button link type="primary" @click="handInfo(scope.row)">查看</el-button>
                  </template>
                </el-table-column>
              </el-table>
            </div>
          </div>
        </el-card>

        <el-card class="box-card" shadow="always" style="background: #fafafa; margin-top: 20px">
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>改造前照片</span>
            </div>
          </template>
          <div class="demo-image">
            <div v-for="(item, index) in beforeElderlyRemodelGalleryList" :key="index" style="display: inline-block; margin-left: 20px">
              <el-image style="width: 200px; height: 200px" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[item.imgUrl]" :src="item.imgUrl"/>
            </div>
          </div>
        </el-card>
        <el-card class="box-card" shadow="always" style="background: #fafafa; margin-top: 20px">
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>改造后照片</span>
            </div>
          </template>
          <div class="demo-image">
            <div v-for="(item, index) in afterElderlyRemodelGalleryList" :key="index" style="display: inline-block; margin-left: 20px">
              <el-image style="width: 200px; height: 200px" :zoom-rate="1.2" :max-scale="7" :min-scale="0.2" :preview-src-list="[item.imgUrl]" :src="item.imgUrl"/>
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="status == '1'"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>验收照片</span>
            </div>
          </template>
          <el-upload
            list-type="picture-card"
            :action="url"
            :limit="10"
            :file-list="checkAcceptElderlyRemodelGalleryList"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :headers="upload.headers"
            :before-upload="beforeUpload"
            :on-success="handleAvatarSuccess"
          >
            <el-icon><Plus /></el-icon>
          </el-upload>
          <el-dialog
            v-model="dialogVisible"
            class="image-view"
            :width="dialogImageWidth + 'px'"
          >
            <img
              class="w-full"
              :src="dialogImageUrl"
              alt="Preview Image"
              @load="adjustDialogWidth"
            />
          </el-dialog>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
          v-if="
            status == '2' && checkAcceptElderlyRemodelGalleryList.length > 0
          "
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>验收照片</span>
            </div>
          </template>
          <div class="demo-image">
            <div
              v-for="(item, index) in checkAcceptElderlyRemodelGalleryList"
              :key="index"
              style="display: inline-block; margin-left: 20px"
            >
              <el-image
                style="width: 200px; height: 200px"
                :zoom-rate="1.2"
                :max-scale="7"
                :min-scale="0.2"
                :preview-src-list="[item.imgUrl]"
                :src="item.imgUrl"
              />
            </div>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 20px"
        >
          <template #header>
            <div class="card-header" style="padding-bottom: 4px">
              <span>验收结果</span>
            </div>
          </template>
          <div>
            <el-form
              ref="checkAcceptformRef"
              :model="checkAcceptForm"
              :rules="rules"
              label-width="90px"
            >
              <el-form-item label="验收结论" prop="checkAcceptStatus">
                <el-radio-group v-model="checkAcceptForm.checkAcceptStatus">
                  <el-radio
                    :disabled="status == '2' ? true : false"
                    v-for="(item, index) in acceptance_status"
                    :key="index"
                    :label="item.value"
                    >{{ item.label }}
                  </el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="备注">
                <el-input
                  v-model="checkAcceptForm.checkAcceptNotes"
                  :disabled="status == '2' ? true : false"
                  type="textarea"
                  :autosize="{ minRows: 2, maxRows: 8 }"
                  placeholder="请输入备注"
                  show-word-limit
                  maxlength="500"
                />
              </el-form-item>
            </el-form>
          </div>
        </el-card>
        <el-card
          class="box-card"
          shadow="always"
          style="background: #fafafa; margin-top: 15px"
        >
          <div style="text-align: right; padding-right: 50px">
            <el-button @click="goCancel">取 消</el-button>
            <el-button
              type="primary"
              v-if="status == '1'"
              style="margin-left: 20px"
              @click="submitFormDebounceHandler"
              >确 定</el-button
            >
          </div>
        </el-card>

        <el-dialog
          v-model="open"
          :title="title"
          append-to-body
          width="800px"
          v-if="open"
          @close="cancel"
          :close-on-click-modal="false"
        >
          <prodect-form
            @closed="cancel"
            :homeBedApplyId="basicInfo.id"
            :formatDate="formatDate"
            :flag="disAbledFlag"
          ></prodect-form>
        </el-dialog>
      </div>
    </el-scrollbar>
  </div>
</template>

<style scoped lang="scss">
.ageReformApply-info {
  padding: 20px;
}
</style>

<script setup name="ageReformApply">
  import { onMounted } from "vue";
  import { debounce } from "@/utils/debounce.js";
  const { proxy } = getCurrentInstance();
  import prodectForm from "../ageReform/project_form.vue";
  import { useRouter, useRoute } from "vue-router";
  import {
    elderlyOrientedRemodelInfo,
    productList,
    updateCheckAcceptInfo,
  } from "@/api/AgeAppropriate";
  import { getToken } from "@/utils/auth";
  const { sys_user_sex, acceptance_result, acceptance_status } = proxy.useDict(
    "sys_user_sex",
    "acceptance_result",
    "acceptance_status"
  );
  const router = useRouter();
  const route = useRoute();
  const loading = ref(false);
  const open = ref(false);
  const title = ref("新增/编辑适老化改造产品");
  const dialogVisible = ref(false);
  const dialogImageUrl = ref("");
  const disabled = ref(false);
  const evaluationCriteriaList = ref([]);
  const beforeElderlyRemodelGalleryList = ref([]);
  const afterElderlyRemodelGalleryList = ref([]);
  const checkAcceptElderlyRemodelGalleryList = ref([]);
  const total = ref(0);
  const status = ref("1");
  const disAbledFlag = ref(false);
  const url = ref(process.env.VUE_APP_BASE_API + "/file/upload/pk-elderly-remodel");
  const upload = reactive({
    // 设置上传的请求头部
    headers: { Authorization: "Bearer " + getToken() },
  });
  const dialogImageWidth = ref("0");
  const data = reactive({
    checkAcceptForm: {},
    formatDate: {},
    basicInfo: {},
    rules: {
      checkAcceptStatus: [
        { required: true, message: "请选择验收结论", trigger: "change" },
      ]
    },
    ageReformItem: {},
  });
  const { checkAcceptForm, rules, basicInfo, formatDate } = toRefs(data);
  /** 提交按钮 */
  const submitFormDebounceHandler = debounce(submitForm, 500);
  function submitForm() {
    proxy.$refs["checkAcceptformRef"].validate((valid) => {
      if (valid) {
        if (checkAcceptElderlyRemodelGalleryList.value.length <= 0) {
          proxy.$modal.msgError("请上传验收图片");
          return false;
        }
        let obj = {
          checkAcceptStatus: checkAcceptForm.value.checkAcceptStatus,
          checkAcceptElderlyRemodelGalleryList:
            checkAcceptElderlyRemodelGalleryList.value,
          id: basicInfo.value.id,
          checkAcceptNotes: checkAcceptForm.value.checkAcceptNotes,
        };
        updateCheckAcceptInfo(obj).then((res) => {
          proxy.$modal.msgSuccess("操作成功");
          router.push("/elderlyReform/checkAccept");
        });
      }
    });
  }
  function handlePictureCardPreview(file) {
    dialogImageUrl.value = file.url;
    dialogVisible.value = true;
  }
  function beforeUpload(file) {
    const isImage = file.type.startsWith("image/");
    if (!isImage) {
      proxy.$modal.msgError("请上传正确的图片格式");
    }
    return isImage;
  }
  function handleAvatarSuccess(response, file) {
    if (response.code == 200) {
      let obj = {
        name: response.data.name,
        imgUrl: response.data.url,
        type: "2",
      };
      checkAcceptElderlyRemodelGalleryList.value.push(obj);
    } else {
      proxy.$modal.msgError("图片上传错误");
    }
  }
  function handleRemove(file, fileList) {
    let arr = [];
    for (let i of fileList) {
      if (i.response) {
        arr.push({
          name: i.response.data.name,
          imgUrl: i.response.data.url,
          type: "2",
          url: i.response.data.url,
        });
      } else {
        arr.push({
          name: i.name,
          imgUrl: i.imgUrl,
          type: "0",
          url: i.imgUrl,
        });
      }
    }

    checkAcceptElderlyRemodelGalleryList.value = arr;
  }

  function handInfo(row) {
    formatDate.value = row;
    formatDate.value.typeId = row.typeId - 0;
    title.value = "查看适老化改造产品";
    disAbledFlag.value = true;
    open.value = true;
  }
  function cancel() {
    open.value = false;
    formatDate.value = {};
    disAbledFlag.value = false;
  }

  function goCancel() {
    router.go(-1);
  }
  function adjustDialogWidth() {
    // Get the width of the image when it is loaded
    const imgElement = document.querySelector(".image-view img");
    if (imgElement) {
      dialogImageWidth.value = imgElement.width;
    }
  }
  function getProductList(id) {
    productList(id).then((res) => {
      evaluationCriteriaList.value = res.productInfo.productList;
      total.value = res.productInfo.totalPrice;
    });
  }

  onMounted(() => {});
  function getInfo(id) {
    elderlyOrientedRemodelInfo(id).then((res) => {
      basicInfo.value.name = res.elderlyOrientedInfo.applyName;
      basicInfo.value.age = res.elderlyOrientedInfo.age;
      basicInfo.value.sex = res.elderlyOrientedInfo.sex;
      basicInfo.value.address = res.elderlyOrientedInfo.address;
      basicInfo.value.id = res.elderlyOrientedInfo.id;
      checkAcceptForm.value.checkAcceptResult = res.elderlyOrientedInfo.checkAcceptResult
      checkAcceptForm.value.checkAcceptNotes = res.elderlyOrientedInfo.checkAcceptNotes
      if (res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList.length > 0) {
        for (let i in res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList) {
          if (res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList[i].imgUrl) {
            res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList[i].url =
              res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList[i].imgUrl;
            beforeElderlyRemodelGalleryList.value =
              res.elderlyOrientedInfo.beforeElderlyRemodelGalleryList;
          }
        }
      }
      if (res.elderlyOrientedInfo.afterElderlyRemodelGalleryList.length > 0) {
        for (let i in res.elderlyOrientedInfo.afterElderlyRemodelGalleryList) {
          if (res.elderlyOrientedInfo.afterElderlyRemodelGalleryList[i].imgUrl) {
            res.elderlyOrientedInfo.afterElderlyRemodelGalleryList[i].url =
              res.elderlyOrientedInfo.afterElderlyRemodelGalleryList[i].imgUrl;
            afterElderlyRemodelGalleryList.value =
              res.elderlyOrientedInfo.afterElderlyRemodelGalleryList;
          }
        }
      }
      if (res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList.length > 0) {
        for (let i in res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList) {
          if (res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList[i].imgUrl) {
            res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList[i].url =
                res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList[i].imgUrl;
            checkAcceptElderlyRemodelGalleryList.value =
                res.elderlyOrientedInfo.checkAcceptElderlyRemodelGalleryList;
          }
        }
      }
    });
  }

  const stopWatch = watch(
    () => route,
    (newVal, oldVal) => {
      status.value = newVal.params.status;
      getInfo(newVal.params.id);
      getProductList(newVal.params.id);
    },
    { immediate: true },
  );

  onBeforeUnmount(() => {
    stopWatch();
  });
</script>
<style scoped lang="scss">
:deep(.el-card.is-always-shadow .el-dialog:not(.is-fullscreen)) {
  width: 100%;
}
:deep(.el-card.is-always-shadow .el-dialog:not(.is-fullscreen) img) {
  width: 100%;
}
</style>
